package com.lisx.module_add_new_word.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.GeneralBasicParams;
import com.baidu.ocr.sdk.model.GeneralResult;
import com.baidu.ocr.sdk.model.WordSimple;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.libbasecoreui.mvp.BaseActivity;
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils;
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils;
import com.lisx.module_add_new_word.R;
import com.lisx.module_add_new_word.adapter.TipsAdapter;
import com.lisx.module_add_new_word.bean.MyDatabase;
import com.lisx.module_add_new_word.bean.WordBean;
import com.lisx.module_add_new_word.databinding.ActivityAddNewWordBinding;
import com.lisx.module_add_new_word.ocr.SecretInitUtil;
import com.lisx.module_add_new_word.utils.QueryUtils;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class AddNewWordActivity extends BaseActivity implements View.OnClickListener {

    private ActivityAddNewWordBinding binding;
    int currentPosition;
    private List<WordBean> wordBeans;
    private MyDatabase myDatabase;
    private ArrayList<String> data = new ArrayList<>();
    private TipsAdapter adapter;
    private String rightResult = "";
    //底部弹窗
    private PopupWindow popupWindow;
    private View contentView;
    private ImageView image_close;
    private Button btnSkip;
    private TextView tv_answer;
    private String rightAnswer = "";

    public static void start(Context context){
        Intent intent = new Intent(context, AddNewWordActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyStatusBarUtils.setStatusBar(this, "#00000000");
        binding = ActivityAddNewWordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        currentPosition = getIntent().getIntExtra("position",0);
        initData();
        String zi = getIntent().getStringExtra("zi");
        binding.tvWord.setText(zi);
        binding.tvGuan.setText("第 " + (this.currentPosition + 1) + " 关");
        binding.ivComplete.setOnClickListener(this);
        binding.tvAgain.setOnClickListener(this);
        binding.btnNext.setOnClickListener(this);
        binding.ivBack.setOnClickListener(this);
        binding.tishi.setOnClickListener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        adapter = new TipsAdapter(this,data);
        binding.tipsList.setLayoutManager(linearLayoutManager);
        binding.tipsList.setAdapter(adapter);


    }

    public void initData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                myDatabase = MyDatabase.getInstance(AddNewWordActivity.this);
                wordBeans = myDatabase.wordBeanDao().getWordList();
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ivComplete) {
            binding.ivRight.setVisibility(View.GONE);
            showLoadingDialog();
//            binding.paintView.setEnabled(false);
            binding.rlBg.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(binding.rlBg.getDrawingCache());
            binding.rlBg.setDrawingCacheEnabled(false);
            saveImageToGallery(bitmap);
        } else if (v.getId() == R.id.btnNext) {
                next();
        } else if (v.getId() == R.id.ivBack) {
            finish();
        }else if (v.getId() == R.id.tv_again) {
            binding.paintView.cleanPoints();
            binding.tvAgain.setVisibility(View.GONE);
            binding.ivComplete.setVisibility(View.VISIBLE);
            binding.tipsList.setVisibility(View.GONE);
            binding.ivRight.setVisibility(View.GONE);
//            binding.ivRight.setVisibility(View.GONE);
//            showLoadingDialog();
////            binding.paintView.setEnabled(false);
//            binding.rlBg.setDrawingCacheEnabled(true);
//            Bitmap bitmap = Bitmap.createBitmap(binding.rlBg.getDrawingCache());
//            binding.rlBg.setDrawingCacheEnabled(false);
//            saveImageToGallery(bitmap);
        }else if (v.getId() == R.id.tishi) {
            String id = wordBeans.get(currentPosition).getIds();
            String answer = QueryUtils.queryTips(AddNewWordActivity.this,id);
            if (answer == null||answer.length() == 0){
                ToastUtils.showShort("本关卡暂无提示！");
                return;
            }
            showPopwindow();
            openPopWindow();
        }
    }

    private void next(){
        binding.paintView.cleanPoints();
        binding.btnNext.setVisibility(View.GONE);
        binding.ivRight.setVisibility(View.GONE);
        binding.tvAgain.setVisibility(View.GONE);
        binding.ivComplete.setVisibility(View.VISIBLE);
        binding.tipsList.setVisibility(View.GONE);
        if (currentPosition < wordBeans.size() - 1) {
            currentPosition++;
        } else {
            ToastUtils.showShort("已经是最后一关,返回第一关开始");
            currentPosition = 0;
        }
        MmkvUtils.save("word_position", currentPosition);
        binding.tvGuan.setText("第 " + (currentPosition + 1) + " 关");
        binding.tvWord.setText(wordBeans.get(currentPosition).getZi_content());
    }

    private void sccs(File file) {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                LogUtils.d("通用识别 onResult--->" + accessToken);
                recognizeGeneralBasic(file);
            }

            @Override
            public void onError(OCRError ocrError) {
                hideLoadingDialog();
                ToastUtils.showShort("获取token失败，请检查网络重试！");
                LogUtils.d("通用识别 onError--->" + ocrError.getMessage());
            }
        }, this, SecretInitUtil.getAppkey(), SecretInitUtil.getSecretKey());

    }

    private void recognizeGeneralBasic(File file) {
        LogUtils.d("简单识别");
        GeneralBasicParams generalResult = new GeneralBasicParams();
        generalResult.setImageFile(file);
        OCR.getInstance(this).recognizeGeneralBasic(generalResult, new OnResultListener<GeneralResult>() {
            @Override
            public void onResult(GeneralResult generalResult) {
                hideLoadingDialog();
                StringBuffer stringBuffer = new StringBuffer();
                for (WordSimple wordSimple : generalResult.getWordList()) {
                    stringBuffer.append(wordSimple);
                }
                binding.ivRight.setVisibility(View.VISIBLE);
                LogUtils.d(stringBuffer.toString());
                String id = wordBeans.get(currentPosition).getIds();
                String answer = QueryUtils.queryAnswer(AddNewWordActivity.this,id);

                System.out.println("answer==================="+answer+" stringBuffer============ "+stringBuffer.toString());
                //判断是否生成新字成功
                if (!TextUtils.isEmpty(stringBuffer.toString()) && answer.contains(stringBuffer.toString())) {
                    rightResult = stringBuffer.toString();
                    getData();
                    binding.ivRight.setImageResource(R.mipmap.icon_zq);
                    binding.btnNext.setVisibility(View.VISIBLE);
                    binding.tvAgain.setVisibility(View.VISIBLE);
                    binding.ivComplete.setVisibility(View.GONE);
                    binding.tipsList.setVisibility(View.VISIBLE);
                    if (adapter != null){
                        adapter.notifyDataSetChanged();
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //成功后记得设置标记位
                            wordBeans.get(currentPosition).setSelect(1);
                            myDatabase.wordBeanDao().updateWordBean(wordBeans.get(currentPosition));
                        }
                    }).start();
                } else {
                    binding.ivRight.setImageResource(R.mipmap.icon_cw);
                }
                /*for (char c : answerBean.answer.toCharArray()) {
                    if (String.valueOf(c).equals(stringBuffer.toString())) {
                        binding.ivRight.setImageResource(R.mipmap.icon_zq);
                        break;
                    }
                }*/
            }

            @Override
            public void onError(OCRError ocrError) {
                hideLoadingDialog();
                binding.ivRight.setVisibility(View.VISIBLE);
                binding.ivRight.setImageResource(R.mipmap.icon_cw);
                ToastUtils.showShort(ocrError.getMessage());
            }
        });
    }

    private void getData() {
        String id = wordBeans.get(currentPosition).getIds();

        String word = "";
        data.clear();

        System.out.println("right==========="+rightResult);
            for (int j = 0;j < wordBeans.size();j++){
                if ((wordBeans.get(j).getZi_content()).contains(rightResult)){
                    word = wordBeans.get(j).getWord();
                    if (word != null&&word.length() > 1){
                        String tips = wordBeans.get(j).getWord();
                        String[] child_tips  = tips.split(",");
                        for (int i = 0;i < child_tips.length;i++){
                            data.add(child_tips[i]);
                        }
                    }
                    break;
                }
            }


    }

    public int saveImageToGallery(Bitmap bmp) {
        File dirFile = new File(getExternalCacheDir().getAbsolutePath() + "/" + "ybhw");
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File file = new File(dirFile, "tupian_jyb.png");//生成同一张图片覆盖之前的
//        File file = new File(dirFile, "tupian"
//                + System.currentTimeMillis() + ".png");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            sccs(file);
            return 2;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            hideLoadingDialog();
        } catch (IOException e) {
            hideLoadingDialog();
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                hideLoadingDialog();
                e.printStackTrace();
            }
        }
        return -1;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:

                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

    }

    /**
     * 显示颜色选择器popupWindow
     */
    private void showPopwindow() {
        //加载弹出框的布局
        contentView = LayoutInflater.from(AddNewWordActivity.this).inflate(
                R.layout.pop_answer, null);

        popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(false);
        //设置可以点击
        popupWindow.setTouchable(true);
        //进入退出的动画，指定刚才定义的style
//        popupWindow1.setAnimationStyle(R.style.mypopwindow_anim_style);
        tv_answer = contentView.findViewById(R.id.tv_answer);
        String id = wordBeans.get(currentPosition).getIds();
        String answer = QueryUtils.queryTips(AddNewWordActivity.this,id);
        rightAnswer = answer.substring(0,1);
        tv_answer.setText(rightAnswer);
        image_close = contentView.findViewById(R.id.close);
        image_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dissPopWindow();
            }
        });
        btnSkip = contentView.findViewById(R.id.btnSkip);
        btnSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dissPopWindow();
                next();
            }
        });
    }


    public void openPopWindow() {
        if (popupWindow != null){
            //从底部显示
            popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
        }
    }

    public void dissPopWindow(){
        if (popupWindow != null){
            popupWindow.dismiss();
        }
    }
}
